from PIL import Image
from aip import AipOcr

def preImg():
    img = Image.open('yzm.png')
    img = img.convert('L')  # P模式转换为L模式(灰度模式默认阈值127)
    count = 189  # 设定阈值
    table = []
    for i in range(256):
        if i < count:
            table.append(0)
        else:
            table.append(1)
    img = img.point(table, '1')
    img.save('yzm1.png')  # 保存处理后的验证码


# 识别码
APP_ID = '25429847'
API_KEY = 'el3fkD7arW9a7FXg4Aks9bck'
SECRET_KEY = '3G4D2iGsrswq8Y9hCUzAuhHur1jYvpbk'
# 初始化对象
client = AipOcr(APP_ID, API_KEY, SECRET_KEY)

# 读取图片
def get_file_content():
    preImg()
    with open('yzm1.png', 'rb') as f:
        return f.read()

def img2str():
    image = get_file_content()
    # 定义参数变量
    options = {'language_type': 'ENG', }  # 识别语言类型，默认为'CHN_ENG'中英文混合
    #  调用通用文字识别
    result = client.basicAccurate(image, options)  # 高精度接口 basicAccurate, 普通接口 basicGeneral
    # result = client.basicGeneral(image, options)  # 高精度接口 basicAccurate, 普通接口 basicGeneral
    return result